function maxLengthWithAtMostTwoRepeats(s) {
    if (s.length <= 2) return s.length;
    
    let left = 0;
    let maxLen = 0;
    const charCount = {};
    
    for (let right = 0; right < s.length; right++) {
        // 增加右指针指向字符的计数
        const char = s[right];
        charCount[char] = (charCount[char] || 0) + 1;
        
        // 当有字符出现超过2次时，移动左指针直到满足条件
        while (charCount[char] > 2) {
            const leftChar = s[left];
            charCount[leftChar]--;
            left++;
        }
        
        // 更新最大长度
        maxLen = Math.max(maxLen, right - left + 1);
    }
    
    return maxLen;
}

// 测试示例
console.log(maxLengthWithAtMostTwoRepeats("abcabcbb")); // 6 ("abcabc")
console.log(maxLengthWithAtMostTwoRepeats("bbbbb"));    // 2 ("bb")
console.log(maxLengthWithAtMostTwoRepeats("pwwkew"));   // 4 ("wwke" 或 "wkew")
console.log(maxLengthWithAtMostTwoRepeats(""));         // 0
console.log(maxLengthWithAtMostTwoRepeats("a"));        // 1
console.log(maxLengthWithAtMostTwoRepeats("abcde"));    // 5